﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace Common.Controls
{
    public partial class CreateAccount : UserControl
    {
        public CreateAccount()
        {
            InitializeComponent();
        }
        StudyManager _studyManager = StudyManager.GetInstance();
        StudyDataClient _studyDataClient = new StudyDataClient();
        public enum Result { Created, Cancelled,UsernameExists };
        public delegate void AccountCreatedOrCancelledDelegate(Result myResult);
        public event AccountCreatedOrCancelledDelegate AcountCreatedOrCancelled;
        
        private void btnCreateAccount_Click(object sender, RoutedEventArgs e)
        {
            btnCreateAccount.IsEnabled = false;
            _studyDataClient.UserAccountCreated += new StudyDataClient.UserAccountCreatedDelegate(delegate(bool Success)
            {
                if (Success)
                {
                    AcountCreatedOrCancelled(Result.Created);
                }
                else
                {
                    AcountCreatedOrCancelled(Result.UsernameExists);
                }
            });
            _studyDataClient.CreateUserAccount(tbUserName.Text, tbPassword.Password);   
        }

        private void btnCancel_Click(object sender, RoutedEventArgs e)
        {
            AcountCreatedOrCancelled(Result.Cancelled);
        }

        private void ValidateControls()
        {            
            btnCreateAccount.IsEnabled = Validate();
        }
        private bool Validate()
        {
            bool Validated = true;
            if (string.IsNullOrEmpty(tbUserName.Text) == true)
                Validated = false;
            if ((string.IsNullOrEmpty(tbPassword.Password) == true)
                || (tbPassword.Password != tbPassword2.Password))
                Validated = false;
            return Validated;
        }

        private void tbUserName_TextChanged(object sender, TextChangedEventArgs e)
        {
            ValidateControls();
        }

        private void tbPassword_KeyUp(object sender, KeyEventArgs e)
        {
            ValidateControls();
        }

        private void tbPassword2_KeyUp(object sender, KeyEventArgs e)
        {
            ValidateControls();
        }
    }
}
